﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NHibernate.Criterion;
using ZDSoft.QLMS.Entity;
using ZDSoft.QLMS.Component;
using ZDSoft.QLMS.Web.Helpers;
using ZDSoft.QLMS.Entity.SystemSetting;

namespace ZDSoft.QLMS.Web.Controllers
{
    public class QuestionController : ControllerBase
    {
        QuestionComponent questionComponent = new QuestionComponent();
        CourseComponent courseComponent = new CourseComponent();
        TypeComponent typeComponent = new TypeComponent();
        IList<Question> CourseQuestions = new List<Question>();
        KnowledgePointComponent knowledgePointComponent = new KnowledgePointComponent();
        public ActionResult Questions(int id)
        {
            IList<ZDSoft.QLMS.Entity.Type> list = typeComponent.FindAll().Where(o => o.IsActive == true).ToList();
            string str = GetZtree(list);
            CourseQuestions = courseComponent.FindByID(id).Questions;
            foreach (Question question in CourseQuestions)
            {
                if (question.Type.IsActive == true)
                {
                    str += "{id:2011" + question.ID + ",pId:" + question.Type.ID + ",name:\"" + question.Title + "\",open: false,url: \"/Question/Update?ID=" + question.ID + "\",target:\"testIframe\"},";
                }
            }
            TempData["ZTree"] = str;
            TempData["ID"] = id;
            return View();
        }

        public string GetZtree(IList<ZDSoft.QLMS.Entity.Type> list)
        {
            string str = "";
            foreach (ZDSoft.QLMS.Entity.Type type in list)
            {
                str += "{id:" + type.ID + ",pId:0" + ",name:\"" + type.Name + "\",open: false,\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/courses.png\"},";
            }
            return str;
        }
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create(string CoureseID)
        {
            IList<ZDSoft.QLMS.Entity.Type> types = new List<ZDSoft.QLMS.Entity.Type>();
            types = typeComponent.FindAll().Where(o => o.IsActive == true).ToList();
            TempData["Ztree"] = GetKnowledgePoint(Convert.ToInt32(CoureseID));
            TempData["Types"] = types;
            TempData["ID"] = CoureseID;
            return View();
        }

        public ActionResult Update(int id)
        {
            IList<ZDSoft.QLMS.Entity.Type> types = new List<ZDSoft.QLMS.Entity.Type>();
            types = typeComponent.FindAll().Where(o => o.IsActive == true).ToList();
            TempData["Types"] = types;
            Question question = questionComponent.FindByID(id);
            TempData["Ztree"] = GetKnowledgePoint(Convert.ToInt32(question.Course.ID));
            return View(question);
        }

        public JsonResult GetCoursePaged(int pageIndex, int pageSize, string strSearchProperty,
            string strSearchCondition, string strSortProperty, string strSortCondition)
        {


            User user = new User();
            user = Helpers.AppHelper.LoginedUser;
            IList<Course> courses = new List<Course>();
            IList<UserCourse> userCourses = new List<UserCourse>();
            if (user.UserCourses != null)
            {
                userCourses = user.UserCourses;
                foreach (UserCourse userCourse in userCourses)
                {
                    Course course = new Course();
                    course = userCourse.Course;
                    courses.Add(course);
                }
            }
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<Course> list = new List<Course>();
            IList<Course> Courses = courseComponent.GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);

            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }

            foreach (Course entity in courses)
            {
                entity.ToJaonResult<Course>();
                list.Add(entity);
            }
            list.Add(new Course() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }

        public JsonResult GetPaged(int pageIndex, int pageSize, string strSearchProperty,
            string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<Question> list = new List<Question>();
            IList<Question> Questions = questionComponent.GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);

            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }

            foreach (Question entity in (IList<Question>)TempData["Question"])
            {
                entity.ToJaonResult<Question>();
                list.Add(entity);
            }
            list.Add(new Question() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }

        public void QuestioneCreate(string Type, string Degree, string Title, string Answers,string KnowledgePointName)
        {
            
            Answer answer = new Answer();
            answer.Content = Answers;
            answer.IsCorrect = true;
            answer.Create();

            KnowledgePoint knowledgePoint = knowledgePointComponent.FindAll().Where(o => o.Name == KnowledgePointName).ToList()[0];
            IList<ZDSoft.QLMS.Entity.Type> types = new List<ZDSoft.QLMS.Entity.Type>();
            types = typeComponent.FindAll().Where(o => o.Name == Type).ToList();
            Entity.Question questions = new Entity.Question();
            questions.Title = Title;
            questions.Type = types[0];
            questions.IsActive = false;
            questions.Degree = (DefficultDegree)int.Parse(Degree);
            questions.Course = courseComponent.FindByID(Convert.ToInt32(TempData["ID"]));
            questions.KnowledgePoint = knowledgePoint;
            questions.Create();
            answer.Question = questions;
            answer.Update();
            TempData["QuestionID"] = questions.ID;
            TempData["QuestionName"] = questions.Title;
        }

        public void ChoiceQuestioneCreate(string Type, string Degree, string Title, string Answers, string CorrectAnswer,string KnowledgePointName)
        {
            IList<Answer> answers = new List<Answer>();
            string[] strs = Answers.Split(',');
            for (int i = 0; i < strs.Length - 1; i++)
            {
                string[] str = strs[i].Split('|');
                Answer answer = new Answer();
                answer.SerialNumber = str[0];
                answer.Content = str[1];
                string[] correctAnswers = CorrectAnswer.Split(',');
                foreach (string correctAnswer in correctAnswers)
                {
                    if (str[0] == correctAnswer)
                    {
                        answer.IsCorrect = true;
                        break;
                    }
                    else
                    {
                        answer.IsCorrect = false;
                    }
                }
                answer.Create();
                answers.Add(answer);
            }
            KnowledgePoint knowledgePoint = knowledgePointComponent.FindAll().Where(o => o.Name == KnowledgePointName).ToList()[0];
            IList<ZDSoft.QLMS.Entity.Type> types = new List<ZDSoft.QLMS.Entity.Type>();
            types = typeComponent.FindAll().Where(o => o.Name == Type).ToList();
            Entity.Question questions = new Entity.Question();
            questions.Title = Title;
            questions.Type = types[0];
            questions.IsActive = false;
            questions.Degree = (DefficultDegree)int.Parse(Degree);
            questions.Course = courseComponent.FindByID(Convert.ToInt32(TempData["ID"]));
            questions.KnowledgePoint = knowledgePoint;
            questions.Create();
            foreach (Answer answer in answers)
            {
                answer.Question = questions;
                answer.Update();
            }
            TempData["QuestionID"] = questions.ID;
            TempData["QuestionName"] = questions.Title;
        }

        public void QuestioneUpdate(string Type, string Degree, string Title, string Answers, int id, string KnowledgePointName)
        {
            KnowledgePoint knowledgePoint = knowledgePointComponent.FindAll().Where(o => o.Name == KnowledgePointName).ToList()[0];
            Question question = questionComponent.FindByID(id);
            question.Title = Title;
            question.KnowledgePoint = knowledgePoint;
            question.Degree = (DefficultDegree)int.Parse(Degree);
            question.Answers[0].Content = Answers;
            question.Answers[0].Update();
            question.Update();
        }
        public void ChoiceQuestioneUpdate(string Type, string Degree, string Title, string Answers, string CorrectAnswer, int id, string KnowledgePointName)
        {
            KnowledgePoint knowledgePoint = knowledgePointComponent.FindAll().Where(o => o.Name == KnowledgePointName).ToList()[0];
            Question question = questionComponent.FindByID(id);
            question.Title = Title;
            question.KnowledgePoint = knowledgePoint;
            question.Degree = (DefficultDegree)int.Parse(Degree);
            question.Update();
            IList<Answer> oldanswers = question.Answers;
            foreach (Answer answer in oldanswers)
            {
                answer.Delete();
            }
            IList<Answer> newanswers = new List<Answer>();
            string[] strs = Answers.Split(',');
            for (int i = 0; i < strs.Length - 1; i++)
            {
                string[] str = strs[i].Split('|');
                Answer answer = new Answer();
                answer.SerialNumber = str[0];
                answer.Content = str[1];
                string[] correctAnswers = CorrectAnswer.Split(',');
                foreach (string correctAnswer in correctAnswers)
                {
                    if (str[0] == correctAnswer)
                    {
                        answer.IsCorrect = true;
                        break;
                    }
                    else
                    {
                        answer.IsCorrect = false;
                    }
                }
                answer.Question = question;
                answer.Create();
            }
        }
        [HttpPost]
        public void Withdraw(int id)
        {
            Question entity = questionComponent.FindByID(id);
            if (entity.IsActive == true)
            {
                entity.IsActive = false;
            }
            else
            {
                entity.IsActive = true;
            }
            entity.Update();
        }
        public ActionResult NULL()
        {
            return View();
        }

        public void Delete(int ID)
        {
            Question question = questionComponent.FindByID(ID);
            IList<Answer> answers = question.Answers;
            foreach (Answer answer in answers)
            {
                answer.Delete();
            }
            question.Delete();
        }

        public String GetID(string TypeName)
        {
            return typeComponent.FindAll().Where(o => o.Name == TypeName).ToList()[0].ID.ToString();
        }

        public String Text()
        {
            return "[{id:2011" + TempData["QuestionID"] + ",name:\"" + TempData["QuestionName"] + "\",open: false,url: \"/Question/Update?ID=" + TempData["QuestionID"] + "\",target:\"testIframe\"}]";
        }


        public string GetKnowledgePoint(int ID)
        {
            IList<KnowledgePoint> KnowledgePoints = knowledgePointComponent.FindAll().Where(o => o.Course.ID == ID).ToList();
            return GetZtree(KnowledgePoints);
        }
        public string GetZtree(IList<KnowledgePoint> list)
        {
            string str = "";
            foreach (KnowledgePoint knowledgePoint in list)
            {
                if (knowledgePoint.Parent == null)
                {
                    str += "{id:" + knowledgePoint.ID + ",pId:0" + ",name:\"" + knowledgePoint.Name + "\",open: \"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/2.png\"},";
                }
                else
                {
                    str += "{id:" + knowledgePoint.ID + ",pId:" + knowledgePoint.Parent.ID + "" + ",name:\"" + knowledgePoint.Name + "\",open: \"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/2.png\" },";

                }
            }
            return str;
        }
    }
}
